<template>
  <div class="page-container">
    <!-- 筛选栏 -->
    <TableFilter v-if="showFilter" @submit="submitFilter" id="qwerqwer"></TableFilter>
    <!-- 表格主体 -->
    <div class="table-container card">
      <!-- 工具栏 -->
      <div class="table-control">
        <el-button type="primary" plain icon="Plus" @click="add">新增</el-button>
        <el-button type="success" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
        <el-button type="danger" plain icon="Delete" @click="batchDelete">批量删除</el-button>
      </div>
      <el-table
        v-loading="loading"
        :key="expandKey"
        :default-expand-all="isExpandAll"
        :data="tableData"
        row-key="name"
        border
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" align="center" width="50" fixed="left" />
        <el-table-column prop="label" label="部门名称" min-width="240" fixed="left" show-overflow-tooltip></el-table-column>
        <el-table-column prop="name" label="部门标识" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="sort" label="序号" align="center" width="80"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="240" show-overflow-tooltip></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="240" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="120">
          <template #default="scope">
            <DictTag :value="scope.row.status" :list="sys_status" :type="scope.row.status == 1 ? 'primary' : 'danger'"></DictTag>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" align="center" width="220" show-overflow-tooltip></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" align="center" width="220" show-overflow-tooltip></el-table-column>

        <el-table-column label="操作" align="center" width="270" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button text type="info" icon="Plus" @click="add(scope.row)">新增</el-button>
              <el-button text type="primary" icon="EditPen" @click="edit(scope.row)">编辑</el-button>
              <el-button text type="danger" icon="Delete" @click="del(scope.row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- <TablePagination
        v-model:paging="dataParams"
        :total="total"
        @update:page-size="handleSizeChange"
        @update:current-page="handleCurrentChange"
      ></TablePagination> -->
    </div>
    <!-- 弹窗 -->
    <TableForm v-model="showForm" :form-init="formInit" :form-mode="formMode" @submit="submitForm"></TableForm>
  </div>
</template>

<script setup name="department">
import { onMounted, ref } from 'vue'
import { departmentFindAll, departmentCreate, departmentUpdate, departmentRemove, departmentRemoveBatch } from '@/api/system/department'
import { ElMessage, ElMessageBox } from 'element-plus'
import { isTruthy } from '@/utils/judge'
import TablePagination from '@/components/TablePagination/TablePagination.vue'
import TableFilter from './components/TableFilter.vue'
import TableForm from './components/TableForm.vue'
import { useDict } from '@/hooks/useDict'
import DictTag from '@/components/DictTag/DictTag.vue'
import { buildTree } from '@/utils'

const { sys_status } = useDict('sys_status')

const loading = ref(true) // 加载中
const dataParams = ref({ pageNum: 1, pageSize: -1, sortField: 'sort', sortOrder: 'ASC' }) // 筛选参数
const tableData = ref([]) // 表格数据
const total = ref(0) // 总数
const showFilter = ref(true) // 头部筛选栏显示
const showForm = ref(false) // 表单弹窗
const formInit = ref({}) // 表单初始值
const formMode = ref('') // 表单模式 add / edit
const batchSelection = ref([]) // 多选

onMounted(() => {
  handleTable(dataParams.value)
})

// 展开/折叠 默认展开
const isExpandAll = ref(true)
const expandKey = ref(0) // 重新渲染表格状态
function toggleExpandAll() {
  isExpandAll.value = !isExpandAll.value
  expandKey.value++
}

// 筛选
function submitFilter(e) {
  Object.assign(dataParams.value, e)
  handleTable(dataParams.value)
}

// 查
async function handleTable(params) {
  loading.value = true
  const res = await departmentFindAll(params)
  const tempData = res.data || []
  tableData.value = buildTree(tempData)
  total.value = res.total
  loading.value = false
}

// 增
function add(row) {
  formInit.value = {} // 置空参数
  if (row?.name) {
    formInit.value = { parent: row.name, sort: row.sort }
  }
  formMode.value = 'add'
  showForm.value = true
}

// 改
function edit(row) {
  formInit.value = row // 携带参数
  formMode.value = 'edit'
  showForm.value = true
}

// 删
function del(row) {
  const { id, name } = row
  ElMessageBox.confirm(`确认删除『 ${name} 』吗？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 确认删除操作
    const deleteRes = await departmentRemove({ id })
    ElMessage({
      type: 'success',
      message: deleteRes?.msg
    })
    refresh()
  })
}

// 刷新
function refresh() {
  // 置空数据
  tableData.value = []
  batchSelection.value = []
  handleTable(dataParams.value)
}

// 多选
function selectionChange(e) {
  batchSelection.value = e.map((item) => item.id)
}

// 批量删除
function batchDelete() {
  if (!isTruthy(batchSelection.value, 'arr')) return
  ElMessageBox.confirm(`确认批量删除所选项吗？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 确认批量删除操作
    const deleteRes = await departmentRemoveBatch({
      ids: batchSelection.value
    })
    ElMessage({
      type: 'success',
      message: deleteRes?.msg
    })
    refresh()
  })
}

// 提交表单
async function submitForm(e) {
  try {
    let result = {}
    switch (e.mode) {
      case 'add':
        // 新增添加
        result = await departmentCreate(e.data)
        break
      case 'edit':
        // 编辑更新
        result = await departmentUpdate(e.data)
        break
    }
    if (result.success) {
      showForm.value = false
      ElNotification({
        type: 'success',
        title: 'Success',
        message: result?.msg
      })
      refresh()
    }
  } catch (error) {
    console.warn(error.msg)
  }
}

// 分页
function handleSizeChange(e) {
  dataParams.value.pageSize = e
  handleTable(dataParams.value)
}
function handleCurrentChange(e) {
  dataParams.value.pageNum = e
  handleTable(dataParams.value)
}
</script>

<style lang="scss" scoped></style>
